package Database;

import java.io.File;
import java.sql.*;
import java.util.Iterator;
import java.util.List;
import java.util.LinkedList;
public class ConnectionPool {
	//host
	private static String filename;
	//list of connections
	private static List<Connection> pool;
	//number of free connection 
	private static int freeCon;
	private static String db="risk.mdb";
	private static ConnectionPool connectionPool;
	//Oracle username and password
	private ConnectionPool(String filename) throws ClassNotFoundException{
		ConnectionPool.filename=filename;
		ConnectionPool.freeCon=0;
		pool=new LinkedList<Connection>();

		Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
	}
	public static boolean Connect() throws ClassNotFoundException{
		if (connectionPool==null)
			connectionPool=new ConnectionPool(db);
		else
			return true;
		if (connectionPool==null)
			return false;
		else return true;
	}
	public static Connection getConnection() throws SQLException, ClassNotFoundException{
		if(freeCon>0){
			freeCon--;
			return pool.remove(freeCon);
		}else{
			String dbURL = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + filename;
			Connection con = DriverManager.getConnection(dbURL, "",""); 
            return con;
		}
	}
	
	
	public static void returnConnection(Connection con){
		pool.add(con);
		freeCon++;
	}
	
	
	public static void closePool() throws DBException{
		if (pool==null)
			return;
		Iterator<Connection> iterator=pool.iterator();
		while(iterator.hasNext()){
			try {
				Connection con=iterator.next();
				con.close();
			} catch (SQLException e) {
				throw new DBException("Unable to close the connection - " + e.toString()); 
			}
		}
	}
}
